#pragma once
#include <iostream>
#include <string>
#include <mysql/mysql.h>
#include "../comm/httplib.h"
#include <jsoncpp/json/json.h>

#include "head_mysql.hpp"
#include "timestamp.hpp"
#include "generateSessionId.hpp"
#include "generateBID.hpp"
#include "../comm/log.hpp"

using namespace httplib;
using namespace ns_log;

void handle_verify(const Request &req, Response &res)
{
    loadCurrentBID();                                       // 启动时加载 currentBID
    time_t TIME_STAMP_END = time(nullptr);                  // 获取当前时间戳
    size_t valid_time = TIME_STAMP_END - *TIME_STAMP_BEGIN; // 计算时间差

    // 解析 JSON 请求体
    Json::Value json_data;
    Json::CharReaderBuilder reader;
    std::istringstream iss(req.body);
    std::string errs;

    if (!Json::parseFromStream(reader, iss, &json_data, &errs))
    {
        res.set_content("无效 JSON", "text/plain");
        res.status = 400;
        return;
    }

    std::string username = json_data["username"].asString();
    std::string verificationCode = json_data["verificationCode"].asString();

    MYSQL *conn = connect_db();
    if (conn == nullptr)
    {
        res.set_content("数据库连接失败", "text/plain");
        res.status = 500;
        return;
    }

    MYSQL_STMT *stmt;
    MYSQL_BIND bind[1];
    MYSQL_BIND result_bind[1];
    bool is_verified;

    // 查询验证码是否过期
    if (valid_time > VALID_TIME)
    {
        // 删除用户逻辑 (已在上方代码中定义)
        std::string delete_query = "DELETE FROM users WHERE username = '" + username + "'";
        if (mysql_query(conn, delete_query.c_str()))
        {
            res.set_content("验证码失效，请重新发送验证码[0]", "text/plain");
            res.status = 500;
        }
        else
        {
            res.set_content("验证码失效，请重新发送验证码[1]", "text/plain");
            res.status = 200;
        }
        return;
    }

    // 验证码验证逻辑 (未过期的情况)
    stmt = mysql_stmt_init(conn);
    if (!stmt)
    {
        LOG(ERROR)<< "mysql_stmt_init() failed\n";
        res.set_content("验证失败", "text/plain");
        res.status = 500;
        mysql_close(conn);
        return;
    }

    const char *query = "SELECT is_verified FROM users WHERE verification_token = ?";
    if (mysql_stmt_prepare(stmt, query, strlen(query)))
    {
        LOG(ERROR) << "mysql_stmt_prepare() failed\n";
        res.set_content("验证失败", "text/plain");
        res.status = 500;
        mysql_stmt_close(stmt);
        mysql_close(conn);
        return;
    }

    memset(bind, 0, sizeof(bind));
    bind[0].buffer_type = MYSQL_TYPE_STRING;
    bind[0].buffer = (char *)verificationCode.c_str();
    bind[0].buffer_length = verificationCode.size();
    mysql_stmt_bind_param(stmt, bind);

    memset(result_bind, 0, sizeof(result_bind));
    result_bind[0].buffer_type = MYSQL_TYPE_TINY;
    result_bind[0].buffer = (char *)&is_verified;
    result_bind[0].is_null = 0;
    result_bind[0].length = 0;
    mysql_stmt_bind_result(stmt, result_bind);

    if (mysql_stmt_execute(stmt) || mysql_stmt_fetch(stmt))
    {
        LOG(ERROR)<< "mysql_stmt_execute() or fetch() failed\n";
        res.set_content("验证失败", "text/plain");
        res.status = 500;
        mysql_stmt_close(stmt);
        mysql_close(conn);
        return;
    }

    mysql_stmt_close(stmt);

    if (is_verified)
    {
        res.set_content("您的帐户已被验证", "text/plain");
    }
    else
    {
        // 更新用户验证状态
        stmt = mysql_stmt_init(conn);
        if (!stmt)
        {
            std::cerr << "mysql_stmt_init() failed\n";
            res.set_content("验证失败", "text/plain");
            res.status = 500;
            mysql_close(conn);
            return;
        }

        const char *update_query = "UPDATE users SET is_verified = TRUE, session_id = ?, BID = ? WHERE verification_token = ?";
        if (mysql_stmt_prepare(stmt, update_query, strlen(update_query)))
        {
            LOG(ERROR)<< "mysql_stmt_prepare() failed\n";
            res.set_content("验证失败", "text/plain");
            res.status = 500;
            mysql_stmt_close(stmt);
            mysql_close(conn);
            return;
        }

        // 生成新的 session_id 和 BID
        std::string session_id = generateSessionId();
        std::string BID = generateBID();

        MYSQL_BIND update_bind[3];
        memset(update_bind, 0, sizeof(update_bind));

        update_bind[0].buffer_type = MYSQL_TYPE_STRING;
        update_bind[0].buffer = (char *)session_id.c_str();
        update_bind[0].buffer_length = session_id.size();

        update_bind[1].buffer_type = MYSQL_TYPE_STRING;
        update_bind[1].buffer = (char *)BID.c_str();
        update_bind[1].buffer_length = BID.size();

        update_bind[2].buffer_type = MYSQL_TYPE_STRING;
        update_bind[2].buffer = (char *)verificationCode.c_str();
        update_bind[2].buffer_length = verificationCode.size();

        mysql_stmt_bind_param(stmt, update_bind);

        if (mysql_stmt_execute(stmt))
        {
            LOG(ERROR)<< "mysql_stmt_execute() failed\n";
            res.set_content("验证失败", "text/plain");
            res.status = 500;
        }
        else
        {
            res.status = 200;
            res.set_content("您的帐户已成功验证，会话数据已更新", "text/plain");
        }

        mysql_stmt_close(stmt);
    }

    mysql_close(conn);
}
